package com.maint.m

import android.util.Log
import com.maint.m.utils.BuildConfig
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import okio.ByteString

// WebSocket 消息回调接口
interface WebSocketMessageListener {
    fun onMessageReceived(message: String)
    fun onBinaryMessageReceived(bytes: ByteString)
    fun onConnectionOpened()
    fun onConnectionClosed(code: Int, reason: String)
    fun onConnectionFailed(t: Throwable)
}

class WebSocketManager private constructor() {
    private var webSocket: WebSocket? = null
    private var isConnecting = false
    private val messageListeners = mutableListOf<WebSocketMessageListener>()

    private val listener = object : WebSocketListener() {
        override fun onOpen(webSocket: WebSocket, response: Response) {
            Log.i("WebSocket", "WebSocket 连接已打开")
            isConnecting = true
            messageListeners.forEach { it.onConnectionOpened() }
        }

        override fun onMessage(webSocket: WebSocket, text: String) {
            Log.i("WebSocket", "收到文本消息: $text")
            messageListeners.forEach { it.onMessageReceived(text) }
        }

        override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
            Log.i("WebSocket", "收到二进制消息")
            messageListeners.forEach { it.onBinaryMessageReceived(bytes) }
        }

        override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
            Log.w("WebSocket", "WebSocket 连接正在关闭: $code, $reason")
            isConnecting = false
            webSocket.close(code, reason)
        }

        override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
            Log.e("WebSocket", "WebSocket 连接失败", t)
            isConnecting = false
            messageListeners.forEach { it.onConnectionFailed(t) }
        }

        override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
            Log.i("WebSocket", "WebSocket 连接已关闭: $code, $reason")
            isConnecting = false
            messageListeners.forEach { it.onConnectionClosed(code, reason) }
        }
    }

    fun connect() {
        if (isConnecting) {
            Log.i("WebSocket", "WebSocket 已连接或正在连接")
            return
        }

        // 根据浏览器中的使用方式，将 token 作为 URL 路径的一部分
        val tokenValue = TokenManager.getCurrentToken()
        val request = Request.Builder()
            .url(BuildConfig.WEBSOCKET_URL + tokenValue)
            .build()

        val client = OkHttpClient()
        webSocket = client.newWebSocket(request, listener)
    }

    fun sendMessage(message: String): Boolean {
        return webSocket?.send(message) ?: false
    }

    fun disconnect() {
        webSocket?.close(1000, "主动关闭")
        isConnecting = false
    }

    // 判断是否连接websocket
    fun isConnected(): Boolean {
        return isConnecting && webSocket != null
    }

    // 注册消息监听器
    fun registerMessageListener(listener: WebSocketMessageListener) {
        if (!messageListeners.contains(listener)) {
            messageListeners.add(listener)
        }
    }

    // 移除消息监听器
    fun unregisterMessageListener(listener: WebSocketMessageListener) {
        messageListeners.remove(listener)
    }

    // 清除所有监听器
    fun clearMessageListeners() {
        messageListeners.clear()
    }

    companion object {
        @Volatile
        private var INSTANCE: WebSocketManager? = null

        fun getInstance(): WebSocketManager {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: WebSocketManager().also { INSTANCE = it }
            }
        }
    }
}
